<?php

class Admin_ArticleCategoryController extends Zend_Controller_Action
{
    private $_model;
    public function init()
    {
        /* Initialize action controller here */
        $this->_model = new Application_Model_DbTable_ArticleCategory();
    }

    public function indexAction()
    {
        // action body
        
        
    }

    public function addAction()
    {
        if(APPLICATION_ENV!="development")
        {
            $this->_redirect($this->view->url(array(
                'module'=>"admin",
                'action'=>"index",
                'controller'=>"index"
            ), null, true));
            die;
        }
        // action body
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("templates/admin/js/fancy-button/fancy-button.js")
        );
        $this->view->headLink()->prependStylesheet(
            $this->view->baseUrl("templates/admin/css/fancy-button/fancy-button.css")
        );
        
        $mdCat = new Application_Model_DbTable_ArticleCategory();
        $p_list = $mdCat->fetchAll();
        
        $options = $mdCat->buildListParent();       
        $form = new Application_Form_ArticleCategory();
        
        $form->parent_id->setMultiOptions($options);
        if($this->_request->isPost()){
            if($form->isValid($_POST)){
                $data = $form->getValues();
                $intro['allow_add'] = $data['sub_add'];
                $intro['allow_del'] = $data['sub_del'];
                $intro['allow_update'] = $data['sub_update'];
                //Save to database
                $row = $mdCat->createRow($data);
                $row->category_alias = Cms_Filter_String::toAlias($row->category_name);
                if(empty($row->admin_name)){
                    $row->admin_name = $row->category_name;
                }
                if($row->parent_id==0){
                    $row->parent_id = null;
                }else{
                    // nếu người dùng chọn danh mục cha thì cập nhật danh mục cha là has_child=1
                    $mdCat->update(array("has_child"=>1),array("idcategories"=>$row->parent_id));
                }
                $row->sub_categories = serialize($intro);                
                $row->save();
                return $this->_redirect(
                    $this->view->url(array(
                        'module' => "admin",
                        'controller'=>"article-category",
                        'action'=> "list"
                    ), null, true)
                );
            }else{
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
                $this->view->formError = 1;
            }
        }
        $this->view->form = $form;
    }

    public function listAction()
    {
        // action body
        $action = $this->_request->getParam("act");
        if($action=="local"){
            $id = intval($this->_request->getParam("idcat"));
            $local = intval($this->_request->getParam("local"));
            $md = new Application_Model_DbTable_ArticleCategory();
            $row = $md->find($id)->current();
            $row->category_local = $local;
            $result = $row->save();
            $this->_helper->json->sendJson($result);
        }
        
        $choice = $this->_request->getParam("choice",null);
        if($choice=="multi")
        {
            $result = null;
            $id = $this->_request->getParam("idcat",null);
            if($id!=null)
            {
                $cat = $this->_model->find($id)->current();
                $cat->category_status = ($cat->category_status)?0:1;
                $result = $cat->save();
            }
            $this->_helper->json->sendJson($result);
        }
        
        
    }

    public function editAction()
    {
        // action body
        $this->view->headScript()->appendFile(
            $this->view->baseUrl("templates/admin/js/fancy-button/fancy-button.js")
        );
        $this->view->headLink()->prependStylesheet(
            $this->view->baseUrl("templates/admin/css/fancy-button/fancy-button.css")
        );
        
        $id = intval($this->_request->getParam("idcat"));
        $mdCat = new Application_Model_DbTable_ArticleCategory();
        $row = $mdCat->find($id)->current();      
        $form = new Application_Form_ArticleCategory();        
        $options = $mdCat->buildListParent();
        unset($options[$row->idcategories]); 
        
        $form->parent_id->setMultiOptions($options);
        $form->submit->setLabel("Lưu lại");
        
        $dataform = $row->toArray();
        $intro = unserialize($row->sub_categories);
        $dataform['sub_add'] = $intro['allow_add'];
        $dataform['sub_del'] = $intro['allow_del'];
        $dataform['sub_update'] = $intro['allow_update'];
        
        $form->populate($dataform);
        if($this->_request->isPost())
        {
            if($form->isValid($_POST))
            {
                $idcat = $form->getValue("idcategories");
                $data = $form->getValues();
                unset($data['idcategories']);
                if($data['admin_name']=="")
                {
                    $data['admin_name'] = $data['category_name'];
                }          
                      
                if($data['parent_id']==0)
                {
                    $data['parent_id']=null;
                }
                $data['category_alias'] = Cms_Filter_String::toAlias($data['category_name']);
                $n_intro['allow_add'] = $form->getValue("sub_add");
                $n_intro['allow_del'] = $form->getValue("sub_del");
                $n_intro['allow_update'] = $form->getValue("sub_update");                
                $data['sub_categories'] = serialize($n_intro);
                
                unset($data['sub_add']);
                unset($data['sub_update']);
                unset($data['sub_del']);
                
                $mdCat->update($data,"idcategories=$idcat");
                
                return $this->_redirect(
                    $this->view->url(array(
                        'module' => "admin",
                        'controller'=>"article-category",
                        'action'=> "list"
                    ), null, true)
                );
            }else{
                $errors = $form->getMessages();
                foreach($errors as $key=>$value){
                    $form->$key->setAttrib("class","error");
                }
                $this->view->formError = 1;
            }
        }
        $this->view->form = $form;
        
    }

    public function delAction()
    {
        // action body
        $id = intval($this->_request->getParam("idcat"));
        $md = new Application_Model_DbTable_ArticleCategory();
        $row = $md->find($id)->current();
        
        $c_cats = $row->findDependentRowset("Application_Model_DbTable_ArticleCategory");
        $c_arts = $row->findDependentRowset("Application_Model_DbTable_Article");
        if($c_cats->count()>0)
        {
            return $this->_helper->json->sendJson(1);
            
        }
        else if($c_arts->count()>0)
        {
            return $this->_helper->json->sendJson(2);
        }
        else if(!$row->delete())
        {
            return $this->_helper->json->sendJson(3);
        }
        else
        {
            return $this->_helper->json->sendJson(0);
        }   
        return $this->_helper->json->sendJson(4);
    }

    public function subListAction()
    {
        // action body
        $idcat = $this->_request->getParam("idcat", null);
        if($idcat==null)
        {
            exit(0);
        }
        
        //Show dữ liệu
        $p_row = $this->_model->find($idcat)->current();        
        $c_rows = $p_row->findDependentRowset("Application_Model_DbTable_ArticleCategory");        
        $this->view->form = $form;
        
        // Thông tin của danh mục cha
        $this->view->p_row = $p_row;
        
        // Option của danh mục con
        $this->view->c_option = unserialize($p_row->sub_categories);
        
        // Danh sách danh mục con
        $this->view->c_rows = $c_rows;
        
        // Xử lý giao diện với quyền đã đc phân
        $acl = Zend_Registry::get("acl");
        $user = Zend_Auth::getInstance()->getIdentity();
        $mdGroup = new Application_Model_DbTable_UserGroup();
        $group =  $mdGroup->find($user->groups_id)->current();
        $role = $group->groups_name;
        
        $rule = new stdClass;
        $rule->allow_add = $acl->isAllowed($role,"admin:article-category","add-subcat");
        $rule->allow_edit = $acl->isAllowed($role,"admin:article-category","edit-subcat");
        $rule->allow_del = $acl->isAllowed($role,"admin:article-category","del-subcat");
        $rule->allow_view = $acl->isAllowed($role,"admin:article-category","sub-list");
        $this->view->rule = $rule;
          
    }
    
    public function addSubcatAction()
    {
        $idcat = $this->_request->getParam("idcat", null);
        $p_row = $this->_model->find($idcat)->current();
        $this->view->p_row = $p_row;
        
        //Tạo form thêm mới danh mục con
        $form = new Application_Form_SubCat();
        $link = $this->view->url(array(
            "module"=>"admin",
            "controller"=>"article-category",
            "action"=>"sub-list"
        ));
        $form->cancel->setAttrib("onclick","window.location='$link'");
        if($this->_request->isPost())
        {
              
            $sub_categories = unserialize($p_row->sub_categories);
              
            if($form->isValid($_POST) && $sub_categories['allow_add'])
            {
                $parent = $p_row->toArray();
                unset($parent['idcategories']);
                $parent['parent_id'] = $p_row->idcategories;
                
                // Tạo dòng mới kế thừa dữ liệu từ cha nó
                $crow = $this->_model->createRow($parent);
                $crow->has_child=0;
                $crow->category_name = $form->getValue("category_name");
                $crow->admin_name = $form->getValue("admin_name");
                if($crow->admin_name=="")
                {
                    $crow->admin_name = $form->getValue("category_name");
                }                
                $idinsert = $crow->save();
                $this->_redirect($link);
                                
            }
            else
            {
                // Báo lỗi nếu tên danh mục để trống
                $errors = $form->getMessages();
                foreach($errors as $key=>$value)
                {
                    $form->$key->setAttrib("class","error");
                }
            }
        }
        $this->view->form = $form;
    }
    
    public function delSubcatAction()
    {
        // action body
        $id = intval($this->_request->getParam("idcat"));
        $md = new Application_Model_DbTable_ArticleCategory();
        $row = $md->find($id)->current();
        
        $c_cats = $row->findDependentRowset("Application_Model_DbTable_ArticleCategory");
        $c_arts = $row->findDependentRowset("Application_Model_DbTable_Article");
        if($c_cats->count()>0)
        {
            return $this->_helper->json->sendJson(1);
            
        }
        else if($c_arts->count()>0)
        {
            return $this->_helper->json->sendJson(2);
        }
        else if(!$row->delete())
        {
            return $this->_helper->json->sendJson(3);
        }
        else
        {
            return $this->_helper->json->sendJson(0);
        }   
        return $this->_helper->json->sendJson(4);
    }
    
    public function editSubcatAction()
    {
        $id = $this->_request->getParam("id", null);
        $result = null;
        if($id!=null)
        {
            $row = $this->_model->find($id)->current();
            $category_name = $this->_request->getParam("cat_name");
            $admin_name = $this->_request->getParam("adm_name");
            if($category_name!="")
            {
                if($admin_name=="")
                {
                    $admin_name = $category_name;
                }
                $row->category_name = $category_name;
                $row->admin_name = $admin_name;
                $result = $row->save();
            }
        }
        
        $this->_helper->json->sendJson($result);
    }
    
}












